package com.xja.seckill.products.service.impl;

import com.xja.seckill.api.vo.ProductVO;
import com.xja.seckill.order.commons.JsonBean;
import com.xja.seckill.products.domain.mapper.SkuMapper;
import com.xja.seckill.products.domain.model.Sku;
import com.xja.seckill.products.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private SkuMapper SkuMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public String reducerStock(Integer productId) {
        Sku sku = SkuMapper.selectByPrimaryKey (productId);
        Integer count = sku.getCount ()-1;
        sku.setCount (count);
        SkuMapper.updateByPrimaryKeySelective (sku);
        return "当前剩余库存"+count;
    }

    @Override
    public JsonBean getProductById(Integer id) {
        ProductVO productVO = new ProductVO ();
        //查询商品表
        Sku sku = SkuMapper.selectByPrimaryKey (id);

        //查询商品表

        //查询品类表

        //查询参数表

        return new JsonBean (0,"ok",sku);
}

    @Override
    public JsonBean openSeckill(Integer id ,Long count) {
        Sku sku = SkuMapper.selectByPrimaryKey (id);
        if (sku.getSeckill ()) {
            return new JsonBean(0,"该商品已开启秒杀,剩余商品："+redisTemplate.opsForValue ().get ("productCount-" + sku.getId ()),null);
        } else if (sku.getCount ()<count){
            return new JsonBean(0,"商品库存不足，剩余库存:"+sku.getCount (),null);
        }
        sku.setSeckill (true);
        SkuMapper.updateByPrimaryKeySelective(sku);
        redisTemplate.opsForValue ().set ("productCount-"+sku.getId (),count);
        return new JsonBean(0,"商品开启秒杀",null);
    }

    @Override
    public JsonBean closeSeckill(Integer id) {
        Sku sku = SkuMapper.selectByPrimaryKey (id);
        sku.setSeckill (false);
        SkuMapper.updateByPrimaryKeySelective(sku);
        redisTemplate.delete("productCount-"+id);
        return new JsonBean(0,"商品关闭秒杀",null);
    }

}
